<?php
namespace app\home\controller;
use think\Controller;
use app\admin\model\User as UserModel;
use app\admin\model\Card as CardModel;
use app\admin\model\Cardrecord as CardrecordModel;
use think\Db;

class User extends Controller
{
    public function index(){
        $openid = "";
        $weixin = new \weixin\wxapi();
        if(!isset($_SESSION['openid']) || $_SESSION['openid']==''){
            
            if (!isset($_GET["code"])){
                $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                $jumpurl = $weixin->oauth2_authorize($redirect_url, "snsapi_base", "123");
                Header("Location: $jumpurl");
                exit();
            }else{
                $access_token_oauth2 = $weixin->oauth2_access_token($_GET["code"]);
                $openid = $access_token_oauth2['openid'];
                session_start();
                $_SESSION['openid'] = $openid;
            }
        }else{
            $openid = $_SESSION['openid'];
        }

        $userinfo = $weixin->get_user_info($openid);
        // var_dump($userinfo);

        if(count($userinfo) <= 2){
            echo "参数有误，请稍候再试！";die;
        }

        if ($userinfo["subscribe"] == 0){
            // $this->assign('title', "请关注我们");
            $url = "http://mp.weixin.qq.com/s/4V3OtkndQgBLthvxhBTXgA";
            // $this->display("follow");
            Header("Location: $url");
        }else{
            //判断绑定
            //$user = M('User');
            //$condition['openid'] = $openid;
            // $condition['redpacket'] = array("neq", "SUCCESS");
            // $condition['status'] = 0;
            //$arr = $user->where($condition)->find();
            $arr = UserModel::where('openid',$openid)->find();
            // var_dump($arr);
            //1. 未绑定
            if (!isset($arr['status']) || ($arr['status'] == -1)){
                $this->assign('openid', $openid);
                $this->assign('userinfo', $userinfo);
                $this->assign('title', "绑定贵人会员");
                //$this->display('bind');
                return $this->fetch('bind');
            }elseif ($arr['status'] == 0){
                //2. 绑定未审核
                $this->assign('title', "审核中");
                $this->assign('page_title', "正在审核中");
                $this->assign('page_description', "请等待审核完成");
                //$this->display("info");
                return $this->fetch('info');
            }else{
                //3. 绑定已审核
                //$card = M("card");
                //$existcard = $card->field('cardid,title')->getField('cardid,title'); 
                $existcard = CardModel::column('cardid,title');
                // var_dump($existcard);
                
                //更新用户已领取卡券
                $data = array('openid' => $openid,
                              // 'card_id' => "pjK6Wjth4UdFkZGE5zonPhDxCDyI",
                              // 'check_consume' => false
                             );
                $result = $weixin->get_user_card_list($data);
                // var_dump($result);
                
                //$cardrecord = M("cardrecord");
                foreach ($result["card_list"] as $value) {
                    // var_dump($value);
                    // $value = $value * 2;
                    $cardid             = $value['card_id'];
                    $data = array();
                    $data['unionid']    = $value['card_id'].$value['code'];
                    $data['openid']     = $openid;
                    $data['nickname']   = $arr['nickname'];
                    $data['headimgurl'] = $arr['headimgurl'];
                    $data['title']      = (isset($existcard[$cardid])?$existcard[$cardid]:"");
                    $data['cardid']     = $value['card_id'];
                    $data['code']       = $value['code'];
                    // var_dump($data);
                    //$cardrecord->add($data);
                    CardrecordModel::create($data);
                }
                //取已领取卡
                //$Model = new \Think\Model();
                //$sql = "SELECT * FROM ".C("DB_PREFIX")."cardrecord WHERE openid =  '$openid'";
                $sql = "SELECT * FROM wx_cardrecord WHERE openid =  '$openid'";
                // var_dump($sql);
                //$catched = $Model->query($sql);
                $catched = Db::query($sql);
                // var_dump($catched);
                
                //取未领卡列表
                //sql = "SELECT * FROM ".C("DB_PREFIX")."card WHERE ".C("DB_PREFIX")."card.cardid NOT IN (SELECT cardid FROM ".C("DB_PREFIX")."cardrecord WHERE openid = '$openid')";
                $sql = "SELECT * FROM wx_card WHERE wx_card.cardid NOT IN (SELECT cardid FROM wx_cardrecord WHERE openid = '$openid')";
                //$uncatched = $Model->query($sql);
                $uncatched = Db::query($sql);
                // var_dump($uncatched);

                $this->assign('openid', $openid);
                $this->assign('userinfo', $arr);
                $this->assign('xcount', count($uncatched));
                $this->assign('uncatched', $uncatched);
                $this->assign('catched', $catched);
                $this->assign('title', "贵人会员券中心");
                //$this->display('card');
                return $this->fetch('card');
            }
        }
	}

    public function bind(){
        // array(6) { ["cardno"]=> string(3) "123" ["fullname"]=> string(2) "11" ["mobile"]=> string(2) "11" ["birthday"]=> string(10) "2017-07-11" ["address"]=> string(4) "adsf" ["openid"]=> string(28) "opLSlwWIajS0Lo8ptNp2fz8u9jwQ" }

        //1. 校验verifycode是否对？
        // var_dump($_POST);
        // var_dump($_SESSION);
        $cardno     = $_POST["cardno"];
        $fullname   = $_POST["fullname"];
        $mobile     = $_POST["mobile"];
        $birthday   = $_POST["birthday"];
        $address    = $_POST["address"];
        $openid     = $_POST["openid"];

        if (empty($cardno) || empty($mobile) || empty($openid)){
            // $this->assign('info', "该订单号不存在或者交易未完成或者订单数据未同步");
            $this->assign('title', "提交失败");
            $this->assign('page_title', "信息不完整");
            $this->assign('page_description', "重要信息必须填写完整");
            //$this->display("warn");
            return $this->fetch("warn");
        }else{
            //$User = M("User");
            //$condition['cardno'] = $cardno;
            //$condition['mobile'] = $mobile;
            //$condition['_logic'] = 'OR';
            //$result = $User->where($condition)->select();
            // $result = DB::table('user')->select(function($query){
            //     $query->where('cardno',$cardno)->whereOr('mobile',$mobile);
            // });
            $result = Db::name('user')->where("cardno='$cardno' or mobile='$mobile'")->select();
            if (count($result) >= 1){
                $this->assign('title', "提交失败");
                $this->assign('page_title', "会员信息已存在");
                $this->assign('page_description', "请勿重复绑定多个微信号");
                //$this->display("warn");
                return $this->fetch("warn");
            }else{
                
                //自动审核机制
                //$member = M("member");
                //$condition['cardno'] = $cardno;
                //$condition['mobile'] = $mobile;
                //$condition['_logic'] = 'AND';
                //$result2 = $member->where($condition)->select();
                // $result2 = DB::table('member')->select(function($query){
                //     $query->where('cardno',$cardno)->where('mobile',$mobile);
                // });
                $result2 = Db::name('user')->where("cardno='$cardno' and mobile='$mobile'")->select();
                // var_dump($result2);
                if (count($result2) == 1){
                    $data = array();
                    $data['openid']     = $openid;
                    $data['nickname']   = $_POST["nickname"];
                    $data['headimgurl'] = $_POST["headimgurl"];
                    $data['cardno']     = $cardno;
                    $data['fullname']   = $fullname;
                    $data['mobile']     = $mobile;
                    $data['birthday']   = $birthday;
                    $data['address']    = $address;
                    $data['status']     = 1;
                    //$User->where("`openid` = '".$openid."'")->save($data); 
                    UserModel::where('openid', $openid)->update($data);
                    
                    
                    $this->assign('title', "提交成功");
                    $this->assign('page_title', "提交成功");
                    $this->assign('page_description', "会员认证成功");
                    //$this->display("success2");
                    return $this->fetch("success2");
                    
                }else{
                    $data = array();
                    $data['openid']     = $openid;
                    $data['nickname']   = $_POST["nickname"];
                    $data['headimgurl'] = $_POST["headimgurl"];
                    $data['cardno']     = $cardno;
                    $data['fullname']   = $fullname;
                    $data['mobile']     = $mobile;
                    $data['birthday']   = $birthday;
                    $data['address']    = $address;
                    $data['status']     = 0;
                    //$User->where("`openid` = '".$openid."'")->save($data);
                    UserModel::where('openid', $openid)->update($data);
                    // $result = $User->add($data, array(), true);

                    $this->assign('title', "提交成功");
                    $this->assign('page_title', "提交成功");
                    $this->assign('page_description', "请等待审核");
                    //$this->display("success");
                    return $this->fetch("success");
                }
            }
        }
	}

    public function sendcard($openid, $cardid){
        $weixin = new \weixin\wxapi();
        // $result1 = $weixin->send_custom_message($openid, "text", "hello");
        $result = $weixin->send_custom_message($openid, "wxcard", array('card_id'=>$cardid));
        // var_dump($send_result);
        // array(2) { ["errcode"]=> int(0) ["errmsg"]=> string(2) "ok" }
        
        if ($result["errcode"] == 0){
            $this->assign('title', "发送成功");
            $this->assign('page_title', "卡券发送成功");
            $this->assign('page_description', "请返回公众号窗口，点击卡券并领取到卡包");
            //$this->display("success");
            return $this->fetch("success");
        }else{
            $this->assign('title', "发送失败");
            $this->assign('page_title', "卡券发送失败");
            $this->assign('page_description', "原因：".$result["errmsg"]);
            //$this->display("warn");
            return $this->fetch("warn");
        }
        exit;
	}

}